<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>GenshinDic</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      li {
        list-style: none;
        font-size: 16px;
      }

      .root {
        height: 95vh;
      }

      .search-box {
        display: flex;
        border: 1px solid #ccc;
        width: 80%;
        height: 38px;
        margin: 10px auto;
        border-radius: calc(infinity * 1px);
      }

      .search-btn {
        width: 30%;
        height: 40px;
        border-radius: calc(infinity * 1px);
        display: flex;
        cursor: pointer;
        justify-content: center;
        align-items: center;
        transition: 0.4s;
      }

      .btn {
        align-items: center;
      }
      .btn::before {
        content: '|';
        margin: 0 10px;
        width: 3px;
        line-height: 40px;
        color: inherit;
      }

      .search-txt {
        border: none;
        background: none;
        outline: none;
        float: left;
        font-size: 14px;
        transition: 0.4s;
        height: 40px;
        line-height: 40px;
        width: 90%;
        padding: 0 6px;
      }

      .search-box:hover {
        box-shadow: 5px 5px 5px 4px rgba(252, 169, 169, 0.6);
      }

      .list {
        height: calc(95vh - 40px);
        overflow: auto;
        /* text-align: center; */
      }

      .empty {
        width: 50vmin;
        height: 50vmin;
        margin: 0 auto;
      }
      .empty-img {
        width: 50vmin;
        height: 50vmin;
      }

      .item {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        /* flex-direction: column; */
        border: 1px solid #ccc;
        padding: 20px;
        margin: 10px;
      }

      .left {
        flex-direction: column;
        display: flex;
        flex-wrap: wrap;
      }

      .right {
        cursor: pointer;
        height: 100%;
        margin: auto 0;
        width: 10%;
        text-align: center;
        /* background-color: lightgreen; */
        transition: scale 0.6s ease;
      }

      .right:hover {
        scale: 1.1;
      }

      .item:hover {
        transition: box-shadow 0.5s;
        box-shadow: 5px 5px 5px 4px rgba(252, 169, 169, 0.6);
      }

      .tag-list {
        display: flex;
        flex-wrap: wrap;
        /* justify-content: ; */
        align-items: center;
        gap: 5px;
        width: 80%;
        margin: 5px auto 0 auto;
      }
      .tag-list-item {
        font-size: 14px;
        padding: 2px 5px;
        border: 1px solid #ccc;
        border-radius: 5px;
        margin: 0 9px;
        /* color: rgba(252, 169, 169, 0.6); */
        cursor: pointer;
      }

      .tag-list-item:hover {
        transition: box-shadow 0.5s;
        box-shadow: 1px 1px 2px 2px rgba(252, 169, 169, 0.6);
      }

      .tag-active {
        color: #fff;
        background-color: rgba(252, 169, 169, 0.6);
      }

      .tags {
        display: flex;
        flex-wrap: wrap;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        gap: 5px;
        margin: 5px 0 0 0;
      }

      .tag {
        padding: 2px 5px;
        border: 1px solid #ccc;
        border-radius: 5px;
        /* color: rgba(252, 169, 169, 0.6); */
        font-size: 16px;
        cursor: pointer;
      }

      .float-btn {
        width: 30px;
        height: 30px;
        text-align: center;
        font-size: 30px;
        position: fixed;
        bottom: 20px;
        right: 100px;
        border: 1px solid #ccc;
        border-radius: 50%;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <button onclick="add(0)" class="add">添加</button>
    <div class="root">
      <div class="search-box">
        <input
          class="search-txt"
          oninput="debouncedInputHandler(event)"
          placeholder="请输入检索词"
          type="text"
        />
      </div>
      <div class="list"></div>
    </div>

    <script>
      // const tagDic = require('./tagDic.js');
      // import tagDic from './tagDic.mjs';
      let listDic = [];
      let showList = [];
      let tagShowList = '';
      let filterTagList = [];

      let tagDic = {
        fontaine: '枫丹',
        'character-main': '角色（可操作）',
        'character-sub': '角色（NPC）',
        dialogue: '对话',
        domain: '秘境',
        'drop-boss': 'Boss凋落物',
        enemy: '敌人',
        drop: '凋落物',
        food: '食物',
        item: '道具',
        event: '活动',
        location: '地名',
        object: '物品',
        'quest-archon': '魔神任务',
        'quest-world': '世界任务',
        'quest-story': '传说任务',
        specialty: '特产',
        weapon: '武器',
        sword: '单手剑',
        artifact: '圣遗物',
        liyue: '璃月',
        title: '称号·职位名·别名等',
        'how-to-call': '称呼',
        inazuma: '稻妻',
        sumeru: '须弥',
        snezhnaya: '至冬',
        facility: '店铺·设施等',
        organization: '团体组织',
        'quest-daily': '每日委托',
        polearm: '长柄武器',
        catalyst: '法器',
        'enemy-boss': 'Boss',
        'living-being': '生物',
        claymore: '双手剑',
        bow: '弓',
        mondstadt: '蒙德',
        sereniteapot: '尘歌壶',
        'talent-material': '天赋养成素材',
        'weapon-material': '武器突破素材',
        khaenriah: '坎瑞亚',
        'artifact-piece': '圣遗物（单件名）',
        dragonspine: '龙脊雪山',
        gemstone: '宝石',
        element: '元素',
        'quest-random': '突发事件',
      };

      const getDic = () => {
        let tagList = Object.keys(tagDic);
        let list = tagList
          .map(
            (tag, index) =>
              `<li class='tag-list-item' onClick='addTagFilter("${tag}","${index}")'>${getTagDic(
                tag,
              )}</li>`,
          )
          .join('');
        tagShowList = '<div class="tag-list">' + list + '</div>';
        document.querySelector('.list').innerHTML = tagShowList;

        // 创建一个 XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();

        // 配置请求
        xhr.open('GET', 'https://dataset.genshin-dictionary.com/words.json ', true); // 第三个参数表示是否异步

        // 设置请求头（可选）
        // xhr.setRequestHeader('Content-Type', 'application/json');

        // 监听请求状态变化
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              // 请求成功，处理响应数据
              listDic = JSON.parse(xhr.responseText);
            } else {
              // 请求失败，处理错误信息
              alert('Error: ' + xhr.status);
              console.error('Error: ' + xhr.status);
            }
          }
        };

        // 发送请求
        xhr.send();
      };

      const searchWord = (e) => {
        let word = e.target.value;
        showList = [];
        if (!word) {
          let tagList = Object.keys(tagDic);
          let list = tagList
            .map(
              (tag, index) =>
                `<li class='tag-list-item ${
                  filterTagList.includes(tag) ? 'tag-active' : ''
                }' onClick='addTagFilter("${tag}","${index}")'>${getTagDic(tag)}</li>`,
            )
            .join('');
          tagShowList = '<div class="tag-list">' + list + '</div>';

          document.querySelector('.list').innerHTML = tagShowList;
          return;
        }
        let reWord = new RegExp(word, 'g');
        listDic.forEach((item) => {
          if (item['en']?.match(reWord) || item['zhCN']?.match(reWord) || item['id']?.match(reWord))
            showList.push(item);
        });
        let listNode = '';
        showList.forEach((item) => {
          let tagNode = '';
          item.tags?.forEach((tag) => {
            if (filterTagList.length === 0 || filterTagList.includes(tag))
              tagNode += `<span class='tag'>${getTagDic(tag)}</span>`;
          });
          if (tagNode) {
            listNode += `
          <li class='item'>
          <div class='left'>
           <span>简体中文:${item['zhCN']}</span>
           <span>英语:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp${item['en']}</span>
           <span>日语:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp${item['ja']}</span>
           <div class="tags">${tagNode}</div>
           </div>
          </li>`;
          }
        });
        listNode === '' &&
          (listNode +=
            '<div class="empty"><img class="empty-img" src="http://121.41.112.199/static/empty.png" alt="empty"></img></div>');
        document.querySelector('.list').innerHTML = listNode;
      };

      function debounce(func, delay = 500) {
        let timeoutId;
        return function (...args) {
          const context = this;

          clearTimeout(timeoutId);

          timeoutId = setTimeout(() => {
            func.apply(context, args);
          }, delay);
        };
      }
      const debouncedInputHandler = debounce(searchWord, 500);

      const add2Book = (object) => {};

      const addTagFilter = (tag, index) => {
        let tagItemNode = document.querySelector('.tag-list').childNodes[index];
        console.log('nide', tagItemNode);
        if (!filterTagList.includes(tag)) {
          filterTagList.push(tag);
          tagItemNode.classList.add('tag-active');
        } else {
          filterTagList = filterTagList.filter((item) => item !== tag);
          tagItemNode.classList.remove('tag-active');
        }
      };

      const getTagDic = (tag) => {
        return tagDic[tag] || tag;
      };

      getDic();

      const add = (i) => {
        if (i >= listDic.length) return;
        // xhr发送请求
        let xhr = new XMLHttpRequest();
        xhr.open('post', 'http://121.41.112.199/genshin/add', true);
        xhr.setRequestHeader('Content-Type', 'application/json');

        xhr.onreadystatechange = function () {
          if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
              add(i + 1);
              console.log(xhr.responseText); // 处理响应数据
            } else {
              add(i + 1);
              console.error('请求失败：' + xhr.status);
            }
          }
        };

        xhr.send(listDic[i]);
      };
    </script>
  </body>
</html>
